#include <qimage.h>
#include <QGLWidget>
#include "qzerotexture.h"
#include <stdio.h>
#include <stdlib.h>

QZeroTexture::QZeroTexture()
{
  id_ = 0;
  width_ = 0;
  height_ = 0;
  initialised_ = false;
}

QZeroTexture::QZeroTexture(const QZeroTexture& tex)
{
  width_ = tex.width();
  height_ = tex.height();
  id_ = tex.id();
  initialised_ = tex.initialised();
}

QZeroTexture::~QZeroTexture()
{
  Delete();
}

void QZeroTexture::Delete() {
  if (initialised_) {
    glDeleteTextures(1, &id_);
    initialised_ = false;
    width_ = -1;
    height_ = -1;
  }
}

bool QZeroTexture::Load(const std::string& szFileName)
{
  QImage theImage;
  if (!theImage.load(szFileName.c_str()))
  {
    return(false);
  }
  theImage = QGLWidget::convertToGLFormat(theImage);
  width_ = theImage.width();
  height_ = theImage.height();

  // Generate texture id.
  glGenTextures(1, &id_);

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // new

  glBindTexture(GL_TEXTURE_2D, id_);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
  glTexImage2D( GL_TEXTURE_2D, 0, 3, theImage.width(), theImage.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, theImage.bits() );

  return (true);
}

void QZeroTexture::Bind()
{
  glBindTexture(GL_TEXTURE_2D, id_);
}

